package com.example.attrimirror.utils;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.example.attrimirror.model.Item;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectionManager {
    private static final String CHANNEL_ID = "medal_notification";
    private static final String CHANNEL_NAME = "勋章获得通知";
    private static final String CHANNEL_DESC = "显示获得新勋章的通知";
    private static final int NOTIFICATION_ID = 1000;

    private Map<String, Integer> items;
    private Context context;
    private final File collectionFile;
    private final Gson gson;

    public CollectionManager(Context context) {
        this.context = context;
        this.items = new HashMap<>();
        this.gson = new GsonBuilder().setPrettyPrinting().create();
        File appDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror");
        File dataDir = new File(appDir, "data");
        this.collectionFile = new File(dataDir, "collection.json");
        
        // 在构造函数中加载仓库数据
        loadCollectionData();
        createNotificationChannel();
    }

    private void loadCollectionData() {
        try {
            String content = new String(java.nio.file.Files.readAllBytes(collectionFile.toPath()));
            System.out.println("Loading collection data: " + content);
            Map<String, Object> data = gson.fromJson(content, 
                new TypeToken<Map<String, Object>>(){}.getType());
            List<Map<String, Object>> itemsList = (List<Map<String, Object>>) data.get("items");

            // 清空当前物品列表
            items.clear();

            // 将仓库数据加载到内存中
            for (Map<String, Object> item : itemsList) {
                String id = (String) item.get("id");
                int number = ((Number) item.get("number")).intValue();
                items.put(id, number);
                System.out.println("Loaded item: " + id + " = " + number);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "读取仓库数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 添加保存数据的方法
    private void saveCollectionData() {
        try {
            // 首先读取完整的仓库数据
            String content = new String(java.nio.file.Files.readAllBytes(collectionFile.toPath()));
            Map<String, Object> data = gson.fromJson(content, 
                new TypeToken<Map<String, Object>>(){}.getType());
            List<Map<String, Object>> itemsList = (List<Map<String, Object>>) data.get("items");

            // 更新数量
            for (Map<String, Object> item : itemsList) {
                String id = (String) item.get("id");
                if (items.containsKey(id)) {
                    item.put("number", items.get(id));
                }
            }

            // 保存回文件
            try (FileWriter writer = new FileWriter(collectionFile)) {
                gson.toJson(data, writer);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "保存仓库数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public int getItemCount(String itemId) {
        return items.getOrDefault(itemId, 0);
    }

    public void addItem(String itemId, Integer count) {
        items.put(itemId, getItemCount(itemId) + count);
        saveCollectionData();  // 保存更改
    }

    public boolean removeItem(String itemId, Integer count) {
        int currentCount = getItemCount(itemId);
        if (currentCount < count) {
            return false;
        }
        items.put(itemId, currentCount - count);
        saveCollectionData();  // 保存更改
        return true;
    }

    public void updateItemNumber(String itemId, int change) {
        items.put(itemId, getItemCount(itemId) + change);
    }

    public Item getItem(String itemId) {
        try {
            String content = new String(java.nio.file.Files.readAllBytes(collectionFile.toPath()));
            Map<String, Object> data = gson.fromJson(content, 
                new TypeToken<Map<String, Object>>(){}.getType());
            List<Map<String, Object>> itemsList = (List<Map<String, Object>>) data.get("items");

            for (Map<String, Object> itemData : itemsList) {
                if (itemId.equals(itemData.get("id"))) {
                    Item item = new Item();
                    item.setId(itemId);
                    item.setName((String) itemData.get("name"));
                    item.setNumber(((Number) itemData.get("number")).intValue());
                    item.setIcon((String) itemData.get("icon"));
                    return item;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "读取物品数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    private void addDailyMedal(int dayOfWeek) {
        try {
            // 读取当前collection数据
            String content = new String(java.nio.file.Files.readAllBytes(collectionFile.toPath()));
            Map<String, Object> data = gson.fromJson(content, 
                new TypeToken<Map<String, Object>>(){}.getType());
            List<Map<String, Object>> itemsList = (List<Map<String, Object>>) data.get("items");

            // 将Calendar.DAY_OF_WEEK转换为对应的勋章ID
            String[] days = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};
            String medalId = "checkin." + days[dayOfWeek];

            // 找到对应的勋章并增加数量
            for (Map<String, Object> item : itemsList) {
                if (medalId.equals(item.get("id"))) {
                    int currentNumber = ((Number) item.get("number")).intValue();
                    item.put("number", currentNumber + 1);
                    break;
                }
            }

            // 保存更新后的数据
            try (FileWriter writer = new FileWriter(collectionFile)) {
                gson.toJson(data, writer);
            }

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "更新签到勋章失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public void addDailyMedal(Calendar calendar) {
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 将 Calendar.DAY_OF_WEEK (1=周日，2=周一，...，7=周六) 转换为我们需要的索引 (0=周日，1=周一，...，6=周六)
        int index = dayOfWeek - 1;
        
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        String medalName = "周" + weekDays[index];
        
        try {
            // 读取当前collection数据
            String content = new String(java.nio.file.Files.readAllBytes(collectionFile.toPath()));
            Map<String, Object> data = gson.fromJson(content, 
                new TypeToken<Map<String, Object>>(){}.getType());
            List<Map<String, Object>> itemsList = (List<Map<String, Object>>) data.get("items");

            // 将Calendar.DAY_OF_WEEK转换为对应的勋章ID
            String[] days = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};
            String medalId = "checkin." + days[index];

            // 找到对应的勋章并增加数量
            for (Map<String, Object> item : itemsList) {
                if (medalId.equals(item.get("id"))) {
                    int currentNumber = ((Number) item.get("number")).intValue();
                    item.put("number", currentNumber + 1);
                    
                    // 显示获得勋章的提示
                    showMedalNotification(medalName);
                    break;
                }
            }

            // 保存更新后的数据
            try (FileWriter writer = new FileWriter(collectionFile)) {
                gson.toJson(data, writer);
            }

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "更新签到勋章失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public int getBallCount() {
        int count = getItemCount("latechecktoken");
        System.out.println("Getting latechecktoken count: " + count);
        return count;
    }

    public boolean hasBall() {
        boolean has = getBallCount() > 0;
        System.out.println("Checking has latechecktoken: " + has);
        return has;
    }

    public boolean consumeBall() {
        if (hasBall()) {
            removeItem("latechecktoken", 1);
            return true;
        }
        return false;
    }

    public void saveData() {
        saveCollectionData();  // 调用原有的私有方法
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription(CHANNEL_DESC);
            
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private void showMedalNotification(String medalName) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.star_on)
            .setContentTitle("获得新勋章")
            .setContentText("恭喜获得" + medalName + "勋章！")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }
}